﻿using Common;
using DBUtility;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseDal
{
    public class UserDal
    {
        static readonly Lazy<UserDal> dal = new Lazy<UserDal>(() => new UserDal());
        public static UserDal Instance { get; } = dal.Value;
        private UserDal() { }

        private const string table1 = "Users";
        private const string table2 = "Department";
        private const string table4 = "Role";
        private const string table5 = "Post";

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from " + table1);
            strSql.Append(" where IsDelete=0 " + strWhere);
            return SqlHelper.Exists(strSql.ToString());
        }

        /// <summary>
        /// 查询SQL语句
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public StringBuilder GetSelectSql(string strWhere = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT t1.ID,t1.UserAccount,t1.UserPwd,t1.UserName,t1.Gender,t1.Phone,t1.Email,t1.CompanyId,t2.FullName as CompanyName,");
            sb.Append("t1.DeptId,t3.FullName as DeptName,t1.RoleId,t4.RoleName,t4.IsAdmain,t1.PostId,t5.PostName,t1.AccountState,");
            sb.Append("t1.Notes,t1.CreateTime,t1.CreateUser,t1.UpdateTime,t1.UpdateUser,t1.IsDelete,");
            sb.Append("t1.DeleteTime,t1.DeleteUser,t1.LastLoginTime,t1.LastLoginIP,t1.AuditState,t1.AuditTime ");
            sb.Append("FROM " + table1 + " t1 ");
            sb.Append("Left Join (Select ID,FullName from " + table2 + " where Category='Company') t2 ");
            sb.Append("ON t1.CompanyId=t2.ID ");
            sb.Append("Left Join (Select ID,FullName from " + table2 + " where Category='Department') t3 ");
            sb.Append("ON t1.DeptId=t3.ID ");
            sb.Append("Left Join " + table4 + " t4 ");
            sb.Append("ON t1.RoleId=t4.ID ");
            sb.Append("Left Join " + table5 + " t5 ");
            sb.Append("ON t1.PostId=t5.ID ");
            sb.Append("WHERE t1.IsDelete=0 ");

            if (!string.IsNullOrEmpty(strWhere))
            {
                sb.Append(strWhere);
            }

            return sb;
        }

        /// <summary>
        /// 根据用户账号获取实体信息（登录用）
        /// </summary>
        /// <param name="useraccount">账号</param>
        /// <returns></returns>
        public Users GetLoginModel(string useraccount)
        {
            StringBuilder sb = GetSelectSql(" and t1.UserAccount=@userAccount");

            SqlParameter[] parameters =
           {
                new SqlParameter("@userAccount",useraccount)
            };
            DataSet ds = SqlHelper.Query(sb.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return CommonOperation.DataTableToModel<Users>(ds.Tables[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateLogin(Users model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + table1 + " SET ");

            sb.Append("LastLoginTime=@lastLoginTime,");
            sb.Append("LastLoginIP=@lastLoginIP ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                 new SqlParameter("@lastLoginTime",model.LastLoginTime.HasValue ? (object)model.LastLoginTime.Value : DBNull.Value),
                 new SqlParameter("@lastLoginIP",string.IsNullOrEmpty(model.LastLoginIP)?DBNull.Value:(object)model.LastLoginIP),
                new SqlParameter("@id",model.ID)
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 分页查询用户信息
        /// </summary>
        /// <param name="pageSize">当前页</param>
        /// <param name="pageIndex">页尺寸</param>
        /// <param name="strWhere">查询条件</param>
        /// <param name="filedOrder">排序字段</param>
        /// <param name="recordCount">记录数</param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder sb = GetSelectSql(strWhere);
            string countSql = PageHelper.CreateCountingSql(sb.ToString());
            recordCount = Convert.ToInt32(SqlHelper.GetSingle(countSql));
            string pageSql = PageHelper.CreatePageSql(recordCount, pageSize, pageIndex, sb.ToString(), filedOrder);
            DataSet ds = SqlHelper.Query(pageSql);
            return ds.Tables[0];
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Users GetModelById(int id)
        {
            StringBuilder sb = GetSelectSql("and t1.ID=@id");
            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id)
            };
            DataSet ds = SqlHelper.Query(sb.ToString(), parameters);
            return CommonOperation.DataTableToModel<Users>(ds.Tables[0]);
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddUser(Users model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO " + table1 + "(");
            sb.Append("UserAccount,UserPwd,UserName,Gender,Phone,Email,CompanyId,DeptId,");
            sb.Append("RoleId,PostId,Notes,CreateTime,CreateUser)");
            sb.Append(" VALUES(");
            sb.Append("@userAccount,@userPwd,@userName,@gender,@phone,@email,@companyId,@deptId,");
            sb.Append("@roleId,@postId,@notes,@createTime,@createUser)");
            SqlParameter[] parameters =
           {
                new SqlParameter("@userAccount",model.UserAccount),
                new SqlParameter("@userPwd",model.UserPwd),
                new SqlParameter("@userName",model.UserName),
                new SqlParameter("@gender",model.Gender),
                new SqlParameter("@phone",model.Phone),
                new SqlParameter("@email",model.Email),
                new SqlParameter("@companyId",model.CompanyId),
                new SqlParameter("@deptId",model.DeptId),
                new SqlParameter("@roleId",model.RoleId),
                new SqlParameter("@postId",model.PostId),
                new SqlParameter("@notes",model.Notes),
                new SqlParameter("@createTime",model.CreateTime),
                new SqlParameter("@createUser",model.CreateUser)
            };
            int res = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return res;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateUser(Users model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + table1 + " SET ");
            sb.Append("UserName=@userName,");
            sb.Append("Gender=@gender,");
            sb.Append("Phone=@phone,");
            sb.Append("Email=@email,");
            sb.Append("CompanyId=@companyId,");
            sb.Append("DeptId=@deptId,");
            sb.Append("RoleId=@roleId,");
            sb.Append("PostId=@postId,");
            sb.Append("Notes=@notes,");
            sb.Append("LastLoginTime=@lastLoginTime,");
            sb.Append("LastLoginIP=@lastLoginIP,");
            sb.Append("UpdateTime=@updateTime,");
            sb.Append("UpdateUser=@updateUser ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@userName",model.UserName),
                new SqlParameter("@gender",model.Gender),
                new SqlParameter("@phone",model.Phone),
                new SqlParameter("@email",string.IsNullOrEmpty(model.Email)?DBNull.Value:(object)model.Email),
                new SqlParameter("@companyId",model.CompanyId),
                new SqlParameter("@deptId",model.DeptId),
                new SqlParameter("@roleId",model.RoleId),
                new SqlParameter("@postId",model.PostId),
                new SqlParameter("@notes",string.IsNullOrEmpty(model.Notes)?DBNull.Value:(object)model.Notes),
                 new SqlParameter("@lastLoginTime",model.LastLoginTime.HasValue ? (object)model.LastLoginTime.Value : DBNull.Value),
                 new SqlParameter("@lastLoginIP",string.IsNullOrEmpty(model.LastLoginIP)?DBNull.Value:(object)model.LastLoginIP),
                new SqlParameter("@updateTime",model.UpdateTime.HasValue ? (object)model.UpdateTime.Value : DBNull.Value),
                new SqlParameter("@updateUser",string.IsNullOrEmpty(model.UpdateUser)?DBNull.Value:(object)model.UpdateUser),
                new SqlParameter("@id",model.ID),
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int DeleteUser(List<string> ids, string userName)
        {
            StringBuilder strSql;
            List<CommandInfo> sqlList = new List<CommandInfo>();
            CommandInfo cmd;
            foreach (string id in ids)
            {
                strSql = new StringBuilder();
                strSql.Append(" update " + table1 + " set ");
                strSql.Append(" IsDelete=1,DeleteTime=GetDate(),DeleteUser='" + userName + "' ");
                strSql.Append(" Where ID=" + id);
                cmd = new CommandInfo(strSql.ToString());
                sqlList.Add(cmd);
            }
            int result = SqlHelper.ExecuteSqlTran(sqlList);
            return result;
        }

        /// <summary>
        /// 修改状态（启用、禁用）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status, string userName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + table1 + " SET ");
            sb.Append("AccountState=@status,");
            sb.Append("UpdateTime=GetDate(),");
            sb.Append("UpdateUser=@updateUser ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@status",status),
                new SqlParameter("@updateUser",userName),
                new SqlParameter("@id",id),
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 用户认证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int AuditUser(string id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Update " + table1 + " SET ");
            sb.Append("AuditState=1,");
            sb.Append("AuditTime=GetDate() ");
            sb.Append("WHERE ID in(@id)");
            SqlParameter[] parameters = {
                new SqlParameter("@id",id),
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

    }
}
